/*
 * Copyright (C) 2017 Pingan, Inc. All Rights Reserved.
 */

package com.pingan.haofang.searchcloud.es.schema.impl;

import com.pingan.haofang.searchcloud.api.schema.IndexSchema;
import com.pingan.haofang.searchcloud.api.schema.SchemaCopyField;
import com.pingan.haofang.searchcloud.api.schema.SchemaField;
import com.pingan.haofang.searchcloud.es.schema.type.FieldMapping;
import com.pingan.haofang.searchcloud.es.schema.type.MetaFieldTypeMapper;

import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * meta field转换器
 *
 * @author zhangbi617
 * @date 2017-07-13
 */
public class MetaFieldTypeConvertor {
    /**
     * fieldMapping
     *
     * @param schema schema
     * @return
     */
    public static List<FieldMapping> convert(IndexSchema schema) {


        Map<String, Set<String>> sourceDestCopyMap = new HashMap<>();
        for (SchemaCopyField copyField : schema.getCopyFields()) {
            Set<String> targetFieldNames = new LinkedHashSet<>();
            targetFieldNames.add(copyField.getDest());
            sourceDestCopyMap.put(copyField.getSource(),targetFieldNames);
        }

        List<FieldMapping> fieldMappings = new LinkedList<>();
        for (SchemaField field : schema.getFields()) {
            FieldMapping fieldMapping = new FieldMapping();
            fieldMapping.setName(field.getName());
            fieldMapping.setDefaultValue(field.getDefaultValue());
            fieldMapping.setCopyTo(sourceDestCopyMap.getOrDefault(field.getName(), new LinkedHashSet<>()));
            fieldMapping.setIndexed(field.isIndexed());
            fieldMapping.setStored(field.isStored());
            fieldMapping.setType(MetaFieldTypeMapper.getEsType(field.getType()));
            fieldMappings.add(fieldMapping);
        }

        return fieldMappings;
    }
}
